package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"zhihu-novel-mgr/chone"
	"zhihu-novel-mgr/modler"
)

func UserAdd(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	author := c.PostForm("author")
	if title == "" || comment == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := modler.Novel{

		Title:   title,
		Comment: comment,
		Author:  author,
	}
	err := modler.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "UserAdd" + strconv.Itoa(int(data.ID))
	var novel modler.Novel
	modler.DB.Where("id=?", data.ID).First(&novel)
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	marshal, _ := json.Marshal(novel)
	chone.Rdb.Set(chone.Ctx, result, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var count int64
	modler.DB.Model(&modler.Novel{}).Count(&count)
	var novel []modler.Novel

	redis_key := "UserList" + strconv.Itoa(page)
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Offset(offset).Limit(size).Find(&novel)
		marshal, _ := json.Marshal(novel)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &novel)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  novel,
		"count": count,
	})
	return
}

func UserDetail(c *gin.Context) {
	id := c.Query("id")
	var novel modler.Novel

	redis_key := "UserDetail" + id
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Where("id=?", id).First(&novel)
		marshal, _ := json.Marshal(novel)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &novel)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": novel,
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var novel modler.Novel
	err := modler.DB.Where("id=?", id).First(&novel).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
		return
	}
}
